<template>
  <div class="customer-adjustment-wrap">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput ref="paramsObj" v-model="paramsObj" :filter-list="filterList" is-show-config show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
        <div style="position: absolute;left: 509px;top: 6px;display:flex;align-items:center;">
          <el-checkbox v-model="isShowMe" style="margin-right: 20px;" @change="queryClick">我发起的</el-checkbox>
        </div>
        <div class="opeator-bar">
          <createBtn v-if="hasRouteAuth('crm:customer:add')" text="新建" @click.native="toCreate"/>
        </div>
      </div>
      <div>
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length"
            ref="tableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            :row-class-name="tableRowClassName"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column align="left" label="审批单号" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.approvalNo" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="客户名称" min-width="120">
              <template slot-scope="scope">
                <div v-if="scope.row.clientName" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                  <ToolTip :content="scope.row.clientName" placement="top-start" is-can-click @handelClick="toDetail(scope.row)" />
                </div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.department | departmentFilter" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="客户创建人" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.createUser" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="备注" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.remark" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <StatusText
                  v-if="scope.row.status || scope.row.status===0"
                  :color="['#FFBC3D', '#FD8546', '#FF4E5F', '#999', '#31CC9C', '#406EFF'][scope.row.status]"
                  :text="scope.row.status | statusFilter"
                />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="审批人" min-width="100">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.approverName" :label="scope.row.approverName" :user-id="scope.row.approverId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="审批时间" min-width="160" prop="approverTime" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.approverTime,'YYYY/MM/DD HH:mm')" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人" min-width="80">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人部门" min-width="150">
              <template slot-scope="scope">
                <ToolTip v-if="scope.row.proposerDepartment && scope.row.proposerDepartment.length" :content="scope.row.proposerDepartment | departmentFilter" placement="top-start" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人职位" min-width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.proposerPost" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请时间" min-width="160" prop="createTime" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm')" placement="top-start" />
              </template>
            </u-table-column>
            <u-table-column :width="130" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div
                  v-loading="scope.row._loading"
                  v-if="scope.row.status === 0 && (scope.row.approverId === userInfo.id || scope.row.proposerId === userInfo.id)"
                  element-loading-spinner="el-icon-loading"
                  class="flex-center loading-container">
                  <template v-if="scope.row.approverId === userInfo.id">
                    <div class="button-text br" @click="toApproval(scope.row, 2)">通过</div>
                    <div class="button-text" @click="toApproval(scope.row, 1)">拒绝</div>
                  </template>
                  <div v-if="scope.row.proposerId === userInfo.id" :class="{'bl': scope.row.approverId === userInfo.id}" class="button-text danger" @click="toDelete(scope.row)">删除</div>
                </div>
                <div v-else-if="scope.row.status === 1 && scope.row.proposerId === userInfo.id" class="button-text danger " @click="toDelete(scope.row)">删除</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!list.isInit" slot="empty" empty-text="暂无数据" mode="table" text-color="#999" style="padding-bottom: 0;" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus">
              <div slot="checkGroup">
                <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
              </div>
            </FilterInput>
            <createBtn v-if="hasRouteAuth('crm:customer:add')" mobile-table text="新建" @click.native="toCreate"/>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
    <ApprovalDialog ref="approvalDialogRef" @freshData="fetchData" />
    <CreateApproval ref="CreateApprovalRef" @freshData="fetchData" />
  </div>
</template>

<script>
// compoments
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import ListTab from '@/components/ListTab';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import CreateApproval from './createApproval';
import ApprovalDialog from './approvalDialog';
// api
import { getCustomerCooperation, getCustomerCooperationTab, delClientCooperation, cooperationApprover } from '@/api/customer';
// mixins
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
// tools
import axios from 'axios';
import { hasRouteAuth } from '@/utils/permission';
import { format } from '@/filters/date';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';

export default {
  components: {
    EmptyPlaceholder, CreateApproval, ApprovalDialog,
    createBtn, btnGroup, ListTab, MoreOpeator
  },
  filters: {
    departmentFilter(data) {
      if (!data || data.length === 0) return '--';
      return data.map(item => item.name).join(',');
    },
    statusFilter(status) {
      return {
        0: '审批中',
        1: '未过审',
        2: '已完成'
      }[status] || '--';
    }
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      sortType: '',
      sortName: '',
      paramsObj: {},
      isShowMe: false,
      isMyApproval: false,
      isMyPending: false,
      tabs: [],
      tabStatus: -1,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      perPage: 20,
      listLoading: false,
      page: 1,
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      cancelToken: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [
        // 输入框
        { keyword: 'clientName', name: '客户名称', labelWidth: '85px', type: 'input' },
        { keyword: 'approvalNo', name: '审批单号', labelWidth: '85px', type: 'input' },
        { keyword: 'createUser', name: '客户创建人', labelWidth: '85px', type: 'input' },
        { keyword: 'proposer', name: '申请人', labelWidth: '85px', type: 'input' }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 150 : 192;
    }
  },
  created() {
    const { clientName, approvalNo } = this.$route.query;
    if (approvalNo) {
      this.$set(this.paramsObj, 'approvalNo', approvalNo);
    }
    if (clientName) {
      this.$set(this.paramsObj, 'clientName', clientName);
    }
    this.fetchData();
  },
  methods: {
    format,
    hasRouteAuth,
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.fetchData(true);
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      params.tabStatus = this.tabStatus;
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortType = this.sortType || '';
      params.sortName = this.sortName || '';
      return params;
    },
    queryTabs() {
      const params = this.formatParams();
      getCustomerCooperationTab(params).then(res => {
        if (res.code === 200) {
          this.tabs = res.data;
        }
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.listLoading = true;
      this.queryTabs();
      if (reset) this.page = 1;
      const params = this.formatParams();
      getCustomerCooperation(params, source.token).then(res => {
        if (res.code === 200) {
          this.list = res.data;
          this.listLoading = false;
        }
        if (this.setSelectRow) this.setSelectRow(res.data.items);
        this.list.isInit = false;
      }).catch(err => {
        this.listLoading = false;
        console.error(err.message);
      });
    },
    toCreate() {
      this.$refs.CreateApprovalRef.openDialog();
    },
    toApproval(row, status) {
      if (status === 1) {
        showModal('是否拒绝该客户的协作申请?', '', {
          iconClass: 'del-icon'
        }).then(() => {
          const data = {
            status,
            id: row.id
          };
          this.$set(row, '_loading', true);
          cooperationApprover(data).then(res => {
            this.$set(row, '_loading', false);
            if (res.code === 200) {
              this.$message.success('操作成功');
              this.fetchData();
            } else {
              this.$message.error(res.message);
            }
          }).catch(() => {
            this.$set(row, '_loading', false);
          });
        }).catch(() => {
          this.$set(row, '_loading', false);
          return false;
        });
      } else {
        this.$refs.approvalDialogRef.openDialog(row, status);
      }
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toDetail(item) {
      const routeUrl = this.$router.resolve({
        name: 'detailCustomer',
        params: { customerId: item.clientId }
      });
      window.open(routeUrl.href, '_blank');
    },
    toDelete(row) {
      showModal('是否确定删除?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        delClientCooperation(row.id).then(_ => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.fetchData();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.customer-adjustment-wrap {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
  }
  & ::v-deep {
    .pointer {
      cursor: pointer;
    }
    .cell-bg-box > .cell {
      height: 20px;
    }
  }
  .opeator-bar {
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    align-items: center;
  }
}
.danger {
  color: red;
}
.loading-container {
  &::v-deep {
    .el-loading-mask {
      display: flex;
      .el-loading-spinner {
        background-image: none !important;
        margin-top: 0 !important;
        top: 50%;
        left: 50%;
        width: 100%;
        height: 100%;
        transform: translate(-50%, -50%);
        @include flexStyle($align: center, $justify: center);
      }
    }
  }
}
</style>
